/**
 * 
 */
package com.desksoft.ecommerce.handler.filter;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

/***************************************
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: 
 * 创建作者：yejw
 * 文件名称：
 * 版本：
 * 功能：
 * 最后修改时间：
 * 修改记录：
 *****************************************/
public class CacheFilter implements Filter {
    
    /**
     * 缓存分钟
     * -1: 不缓存
     * 0:默认
     * >0:缓存分钟数
     */
    private int cacheMin;
    
    /* (non-Javadoc)
     * @see javax.servlet.Filter#destroy()
     */
    @Override
    public void destroy() {
        //nothing to do
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // 设置缓存时间
        if (cacheMin == -1) {
            // 不缓存
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Cache-Control", "no-cache");
            httpResponse.setHeader("Pragma", "no-cache");
            httpResponse.setDateHeader("Expires", 0);
        } else if (cacheMin > 0) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MINUTE, cacheMin);
            httpResponse.setHeader("Cache-Control", "max-age=" + (this.cacheMin * 60));//second
            httpResponse.setDateHeader("Expires", cal.getTimeInMillis());
        } else {
            // ignore
        }

        chain.doFilter(request, response);
    }

    /* (non-Javadoc)
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    @Override
    public void init(FilterConfig config) throws ServletException {
        String time = config.getInitParameter("time");
        try {
            this.cacheMin = Integer.parseInt(StringUtils.trim(time));
        } catch (NumberFormatException e) {
            this.cacheMin = 0;
            e.printStackTrace();
        }
    }
}

